#testtool 
#created by dirkcai
import os
import sys
import socket
import random
import threading
import time

def Test(index, reqcount, host, port, pkglen):
	startime = time.time()	
	##construct pkg
	if pkglen > 64:
		data = "hello," * ( (pkglen / len("hello,")) - 1 )
		data += str( random.randrange(0,10000) )
	else:
		data = "hello, just a test pkg"

	for i in range(0, reqcount):
		##connect server, send testing pkg and recv writeback pkg, then close
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.connect( (host,port) );
		s.send(data)
		datacheck = s.recv( pkglen )
		s.close()
		##diff the data
		if data == datacheck:
			print i," ok"
		else:
			print "fail data: ",data
			print "fail datacheck: ",datacheck
	
	print "thread[", index ,"] end"
	endtime = time.time();
	runtime = endtime-startime
	print "total time: ",runtime

def Control(threadcount, reqcount, host, port, pkglen):
	##creat threads
	threads = []
	for i in range(0,threadcount):
		threads.append( threading.Thread(target=Test,args=(i, reqcount, host, port, pkglen)))
	
	##start threads
	for i in range(0,threadcount):
		print "thread ",i," is running"
		threads[i].start()
	

## top level code
if len(sys.argv) < 6:
	print "argv[1] threadcount"
	print "argv[2] reqcount"
	print "argv[3] hostip"
	print "argv[4] port"
	print "argv[5] pkglen"
else:
	Control( int(sys.argv[1]), int(sys.argv[2]), sys.argv[3], int(sys.argv[4]), int(sys.argv[5]) )

